package com.wc.test.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.wc.test.bean.User;
import com.wc.test.service.UserServiceImpl;
import com.wc.test.util.Page;
import org.apache.log4j.PropertyConfigurator;

public class UserPageApiServlet extends HttpServlet {
	
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		// 获取发请求的url地址
		String url = request.getRequestURI();
		// 从url地址获取到该类的方法名
		String methodName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
		Method method = null;
		try {
			// 通过反射，执行本类的方法
			method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		} catch (Exception e) {
			System.out.println("调用方法出错：" + e.getMessage());
		}

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	 @Override  
	    public void init() throws ServletException {  
	        // TODO Auto-generated method stub  
	        super.init();  
	        String prefix = getServletContext().getRealPath("/");  
	        String file = getInitParameter("log4j-init-file");  
	        if (file != null) {  
	            System.out.println("read log4j.properties:"+prefix + file);  
	            PropertyConfigurator.configure(prefix + file);  
	        }  
	    }  
	/**
	 * 新增用户
	 * 
	 * @param request
	 * @param response
	 */
	private void addUser(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User newUser = new User();
		//User oldUser = UserServiceImpl.getInstance().registerUser(username);
		newUser.setUsername(username);
		newUser.setPassword(password);
			// 调用新增用户的方法
			boolean result = UserServiceImpl.getInstance().saveUser(newUser);
			if (result) {
				System.out.println("新增成功");
				// 最后重定向到用户列表页面
				try {
					response.sendRedirect("userList.action?userName=&page=1");
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("新增失败");
			}
		

	}

	/**
	 * 删除用户
	 * 
	 * @param request
	 * @param response
	 */
	private void removeUser(HttpServletRequest request, HttpServletResponse response) {
		// 从jsp页面获取到该用户的id
		String ids = request.getParameter("id");
		int id = Integer.parseInt(ids);
		boolean result = UserServiceImpl.getInstance().removeUser(id);
		if (result) {
			System.out.println("删除成功");
			// 最后重定向到用户列表页面
			try {
				response.sendRedirect("userList.action?userName=&page=1");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("删除失败");
		}
	}

	/**
	 * 获取一个用户
	 * 
	 * @param request
	 * @param response
	 */
	
	private void getUser(HttpServletRequest request, HttpServletResponse response) {
		// 从jsp页面获取到该用户的id
		String ids = request.getParameter("id");
		int id = Integer.parseInt(ids);
		// 调用根据id查询一个用户的方法
		User user = UserServiceImpl.getInstance().getUserByID(id);
		/*
		 * 方法二
		 */
		//将查到的user对象转换成json对象
		 JSONObject json = JSONObject.fromObject(user);
		 try {
			 //最后将转换好的对象发送出去
			response.getWriter().print(json);
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 修改用户
	 * 
	 * @param request
	 * @param response
	 */
	private void updateUser(HttpServletRequest request, HttpServletResponse response) {
		// 从jsp页面获取到需要修改的值
		String ids = request.getParameter("id");
		int id = Integer.parseInt(ids);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 调用修改方法
		boolean result = UserServiceImpl.getInstance().updateUser(new User(id, username, password));
		if (result) {
			System.out.println("修改成功");
			// 需要重定向到列表页面,如果需要将提示信息存到request中，需要转发
			try {
				response.sendRedirect("userList.action?userName=&page=1");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("修改失败");
		}

	}

	/**
	 * 分页查询用户
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void userList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取前端的数据
		String userName = request.getParameter("userName");

		String pages = request.getParameter("page");
		int pageIndex = Integer.parseInt(pages);
		
		//第一次走这个请求，一定是第一页，页面大小固定的
		int pageSize = 5;
		int currentPageNo = 1;

		//获取用户数量
		int totalCount = UserServiceImpl.getInstance().findCount();
		List<User> userList = null;

		//总页数支持
		Page page = new Page();
		page.setCurrentPageNo(currentPageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(totalCount);

		//最大页数
		int totalPageCount = (totalCount / pageSize) + 1;

		//给page参数赋初始值
		currentPageNo = pageIndex;
		
		//获取用户列表展示
		userList = UserServiceImpl.getInstance().getUserList(userName, User.ASC, pageIndex, pageSize);
		
		request.setAttribute("userList", userList);
		
		int[] pageArray = new int[totalPageCount];
		request.setAttribute("pageArray", pageArray);
		//存值给userList页面的页数赋值
		request.setAttribute("currentPageNo", currentPageNo);
		request.setAttribute("totalPageCount", totalPageCount);
		request.setAttribute("pageIndex", pageIndex);
		//返回前端
		try {
			request.getRequestDispatcher("userList.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取前端输入的用户名和密码
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		User user = UserServiceImpl.getInstance().login(loginName, password);
		if (user != null) {
			//将用户存到session
			request.getSession().setAttribute("user", user);
			//跳转到用户列表
			response.sendRedirect("userList.action?userName=&page=1");
		}else {
			request.setAttribute("msg", "用户名或者密码错误");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		
	}
	
	private void getUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String registerUsername = request.getParameter("registerUsername");
		User user = UserServiceImpl.getInstance().registerUser(registerUsername);
		//将查到的user对象转换成json对象
		 JSONObject json = JSONObject.fromObject(user);
		 try {
			 //最后将转换好的对象发送出去
			response.getWriter().print(json);
			System.out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
		
	}
	
	private void registerUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String registerUsername = request.getParameter("registerUsername");
		String registerPassword = request.getParameter("registerPassword");
		User user = new User();
		user.setUsername(registerUsername);
		user.setPassword(registerPassword);
		boolean result = UserServiceImpl.getInstance().saveUser(user);
		if (result) {
			request.setAttribute("msg", "注册成功");
			response.sendRedirect("login.jsp");
		}else {
			request.setAttribute("msg", "注册失败");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
		
		
	}
	private void goutUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute("user");
		response.sendRedirect("login.jsp");
	}


}
